package com.ruoyi.web.controller.module.dynamic;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.dynamic.domain.Dynamic;
import com.ruoyi.dynamic.service.IDynamicService;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeUserService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 动态信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/dynamic/dynamic")
public class DynamicController extends BaseController
{
    @Autowired
    private IDynamicService dynamicService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IEmployeeUserService employeeUserService;

    /**
     * 获取动态列表
     */
    @PostMapping("/dynamicList")
    public TableDataInfo list(@RequestBody Dynamic dynamic, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            dynamic.setShopId(shopId);
        }
        startPageByPost();
        List<Dynamic> list = dynamicService.selectDynamicList(dynamic);
        if(SecurityUtils.isLogin()){
            Long userId = SecurityUtils.getUserId();
            if (StringUtils.isNotNull(userId)){
                for(Dynamic dy : list){
                    String key = CacheConstants.CUSTOMER_COLLECT_DYNAMIC + userId.toString() + "_" + dy.getDynamicId().toString();
                    JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject((key));
                    if (StringUtils.isNotNull(arrayCache))
                    {
                        dy.setIsLike(UserConstants.YES);
                    }else{
                        dy.setIsLike(UserConstants.NO);
                    }
                }
            }
        }
        return getDataTable(list);
    }

    @Log(title = "动态管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:export')")
    @PostMapping("/dynamicExport")
    public void export(HttpServletResponse response, Dynamic dynamic)
    {
        List<Dynamic> list = dynamicService.selectDynamicList(dynamic);
        ExcelUtil<Dynamic> util = new ExcelUtil<Dynamic>(Dynamic.class);
        util.exportExcel(response, list, "动态数据");
    }

    @PostMapping("/dynamicImportTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Dynamic> util = new ExcelUtil<Dynamic>(Dynamic.class);
        util.importTemplateExcel(response, "动态数据");
    }

    /**
     * 根据动态编号获取详细信息
     */
    @GetMapping(value = { "/", "/{dynamicId}" })
    public AjaxResult getInfo(@PathVariable(value = "dynamicId", required = false) Long dynamicId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(dynamicId))
        {
            Dynamic dynamic = dynamicService.selectDynamicById(dynamicId);
            Long userId = SecurityUtils.getUserId();
            if(StringUtils.isNotNull(userId)){
                String key1 = CacheConstants.CUSTOMER_COLLECT_DYNAMIC + userId.toString() + "_" + dynamic.getDynamicId().toString();
                JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject((key1));
                if (StringUtils.isNotNull(arrayCache))
                {
                    dynamic.setIsLike(UserConstants.YES);
                }else{
                    dynamic.setIsLike(UserConstants.NO);
                }
            }
            ajax.put(AjaxResult.DATA_TAG, dynamic);
        }
        return ajax;
    }

    /**
     * 新增动态
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:add')")
    @Log(title = "动态管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Dynamic dynamic, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            dynamic.setShopId(shopId);
        }
        dynamic.setCreateBy(getUsername());
        return toAjax(dynamicService.insertDynamic(dynamic));
    }

    /**
     * 修改动态
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:edit')")
    @Log(title = "动态管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Dynamic dynamic)
    {
        dynamic.setUpdateBy(getUsername());
        return toAjax(dynamicService.updateDynamic(dynamic));
    }

    /**
     * 发布动态
     */
    @PostMapping("/dynamicPublish")
    public AjaxResult dynamicPublish(@Validated @RequestBody Dynamic dynamic, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            dynamic.setShopId(shopId);
        }
        // 当前登录用户
        Long userId = SecurityUtils.getUserId();
        dynamic.setUserId(userId);
        dynamic.setStatus(UserConstants.STATUS_AUDIT);
        String isAudit = configService.selectConfigByKey("app.dynamic.isAudit");
        // 设置否，所有都不需要审核；设置是，则会判断哪些不需要审核；
        if(isAudit.equals(UserConstants.NO)){
            // 不需要审核动态
            dynamic.setStatus(UserConstants.STATUS_APPROVE);
        }else{
            // 需要审核动态
            EmployeeUser user = employeeUserService.selectUserById(userId);
            if(user.getIsDynamicAudit().equals(UserConstants.NO)){
                // 不需要审核动态
                dynamic.setStatus(UserConstants.STATUS_APPROVE);
            }
        }
        dynamic.setCreateBy(getUsername());
        return toAjax(dynamicService.insertDynamic(dynamic));
    }

    /**
     * 删除动态
     */
    @PostMapping("/dynamicDelete")
    public AjaxResult remove(@RequestBody Dynamic dynamic)
    {
        // 当前登录用户
        Long userId = SecurityUtils.getUserId();
        if(userId != dynamic.getUserId()){
            return error("操作失败：无权限");
        }
        Long[] dynamicIds = new Long[1];
        dynamicIds[0] = dynamic.getDynamicId();
        return toAjax(dynamicService.deleteDynamicByIds(dynamicIds));
    }

    /**
     * 删除动态
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:remove')")
    @Log(title = "动态管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dynamicIds}")
    public AjaxResult remove(@PathVariable Long[] dynamicIds)
    {
        return toAjax(dynamicService.deleteDynamicByIds(dynamicIds));
    }

    /**
     * 审核状态修改
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:edit')")
    @Log(title = "动态管理 - 审核状态修改", businessType = BusinessType.UPDATE)
    @PostMapping("/dynamicChangeStatus")
    public AjaxResult changeStatus(@RequestBody Map<String, String> params)
    {
        String dynamicIds = params.get("dynamicIds");
        String status = params.get("status");
        String[] arr = dynamicIds.split(",");
        for(int i = 0; i < arr.length; i++){
            Dynamic dynamic = dynamicService.selectDynamicById(Long.parseLong(arr[i]));
            dynamic.setUpdateBy(getUsername());
            dynamic.setStatus(status);
            dynamicService.updateDynamicStatus(dynamic);
        }
        return AjaxResult.success();
    }

    /**
     * 上架状态修改
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:edit')")
    @Log(title = "动态管理 - 上架状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/dynamicChangeActive")
    public AjaxResult changeActive(@RequestBody Dynamic dynamic)
    {
        dynamic.setUpdateBy(getUsername());
        return toAjax(dynamicService.updateDynamicActive(dynamic));
    }
}
